import React, { useState } from 'react';
import { Modal, Form, Row, Col, Upload, message, Button } from 'antd';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import { UploadOutlined } from '@ant-design/icons';
import { ASelect, ASelectOptionType } from '@/components/SelfComp';
import { DataItem, FormModalProps } from '@/types/global';
import { ImportTradeTaskRecord } from '@/types/workbench';
import { formLayout, modalFormItemLayout } from '@/utils/commons';

type AddTradeTaskProps<T> = FormModalProps<T> & {
  downloadTemplateFile: (fileName: string) => void;
}

type AddTradePropsEx<T> = Omit<AddTradeTaskProps<T>, 'formData'>;

type ImportTradeTaskFormValue = ImportTradeTaskRecord

const FormItem = Form.Item;
const templateFileCnName = '交易任务模板';
const templateFileEnName = 'trade_task_template.xlsx';

const templateTypeOptions: DataItem[] = [
  { key: '1', value: templateFileCnName },
]

/**
 * 批量导入交易任务，导入会校验交易是否属于需求对应的集群应用
 * <p>根据excel模板填写数据，然后上传excel，实现批量导入</p>
 * 
 * @param props 
 * @returns 
 */
const ImportTradeTaskModal: React.FC<AddTradePropsEx<ImportTradeTaskFormValue>>  = (props) => {
  // 上传的文件列表
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [templateName, setTemplateName] = useState<string>(templateFileCnName);
  const [form] = Form.useForm<ImportTradeTaskFormValue>();

  const onOk = () => {
    form.validateFields().then(fieldsValue => {
      console.info(fieldsValue);
      const values = {
        ...fieldsValue
      };
      console.log('Received values of form: ', values);
      console.log(fileList);
      if (fileList.length < 1) {
        message.warn('请先选择一个文件');
        return;
      }
      if (fileList.length > 1) {
        message.warn('一次只能上传一个文件');
        return;
      }
      const { onHandlerOK } = props;
      if (onHandlerOK) {
        const formData = new FormData();
        formData.append('data', JSON.stringify(values));
        formData.append('file', fileList[0] as RcFile);
        onHandlerOK(formData);
      }
    }).catch();
  };

  const onCancel = () => {
    // 先清除form表单
    form.resetFields();
    const { onHandlerCancel } = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  /**
   * 交易所属系统栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const templateTypeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    // console.log('templateTypeChange', value);
    if (value === '1') {
      // 交易任务模板
      setTemplateName(templateFileCnName);
    }
    // 其实可以筛选集群
    // 但这里暂时不做此功能
  }

  /**
   * 点击下载导入模板文件
   */
  const importNameClick = () => {
    // console.log('importNameClick', afaVisible);
    // 下载文件
    const { downloadTemplateFile } = props;
    if (downloadTemplateFile) {
      downloadTemplateFile(templateFileEnName);
    }
  }

  const { colon, modalTitle, modalWidth, modalVisible, loading } = props;
  const formItemLayout = modalFormItemLayout;
  // 是否有表格勾选数据传进来，保证传进的值不为undefined
  // console.info(formData);
  const uploadTip = '请上传交易任务模板格式的文件';
  const uploadProps: UploadProps = {
    onRemove: file => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: file => {
      setFileList([...fileList, file]);
      return false;
    },
    fileList,
    maxCount: 1,
  };

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      maskClosable={false}
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}>
      <Form layout={formLayout} form={form}>
        <Row>
          <Col span={12}>
            <FormItem label='模板类型' name='templateType' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '模板类型必输' }
              ]}
              initialValue={'1'}
            >
              <ASelect dataSource={templateTypeOptions} onChange={templateTypeChange}/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='导入模板下载' name='importName' {...formItemLayout} colon={colon}>
              <a title='点击下载模板并填写' onClick={() => importNameClick()}>{templateName}</a>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='上传文件' valuePropName='fileList' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '必须上传文件' },
              ]}
            >
              <Upload
                {...uploadProps}
              >
                <Button icon={<UploadOutlined />} title={uploadTip}>点击上传</Button>
              </Upload>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}

export default ImportTradeTaskModal;